#include "PetsBank.h"
#include <string>
#include "GameConfig.h"
#include "Config.h"
#include "pugixml.hpp"
#include "PetFactory.h"

using namespace pugi;

PetBank::PetBank(void)
{
	_listPetFactories = NULL;
	_listPetId = NULL;
}


PetBank::~PetBank(void)
{
	CC_SAFE_RELEASE(_listPetFactories);
	CC_SAFE_RELEASE(_listPetId);
}

PetBank* PetBank::sharedPetBank()
{
	if (!_instance)
		_instance = new PetBank();
	return _instance;
}


void PetBank::initBank()
{
	setPetFactories(CCDictionary::create());
	setPetIds(CCArray::create());

	// Stuff with xml
	std::string data = std::string(dynamic_cast<CCString*>(GameConfig::sharedGameConfig()->getConfigData()->objectForKey(CONFIG_PETS))->getCString());
	xml_document doc;
	xml_parse_result result = doc.load(data.c_str());
	CCAssert(result.status == status_ok, "FAILD");
	
	xml_node node = doc.child("Root").child("Pets");
	
	for (xml_node i = node.child("Pet"); i; i = i.next_sibling("Pet"))
	{
		PetFactory* pFactory = PetFactory::create();
		pFactory->parseXml(i);
		_listPetFactories->setObject(pFactory, pFactory->getId()->getCString());
		_listPetId->addObject(pFactory->getId());
	}
}

void PetBank::clearBank()
{
	delete _instance;
	_instance = NULL;
}



PetFactory* PetBank::getPetFactory( char* id )
{
	return dynamic_cast<PetFactory*>(_listPetFactories->objectForKey(id));
}

CCString* PetBank::getPetIdByIndex( int index )
{
	if (index < 0)
		index = 0;
	else if (index > _listPetId->count() - 1)
		index = _listPetId->count() - 1;
	return dynamic_cast<CCString*>(_listPetId->objectAtIndex(index));
}

PetBank* PetBank::_instance = NULL;
